"use client"

import { ContentBlock, Editor, EditorState, Modifier, DefaultDraftBlockRenderMap } from "draft-js"
import { useCallback, useEffect, useRef, useState } from "react"
import RichEditorToolbar from "./RichEditorToolbar"
import { AtomicImage, imageBlockName } from "./toolbars/IMAGE"
import UiModal from "../ui/UiModal"
import UiButton from "../ui/UiButton"
import Immutable from "immutable"
import { styled } from "@stitches/react"

const StyledHeaderOne = styled("h1", { fontSize: 32, fontWeight: 700 })
const StyledHeaderTwo = styled("h2", { fontSize: 26, fontWeight: 700 })
const StyledHeaderThree = styled("h3", { fontSize: 20, fontWeight: 700 })
const headerWrapper = (Component: any) => {
    const Result = ({ ...props }) => {
        const ref = useRef<HTMLDivElement>();
        useEffect(() => {
            if (!ref.current) return;
            const id = props["data-offset-key"].split("-")[0];
            ref.current.id = id;
        }, [props.children, ref.current]);
        return (
            <Component ref={ref}>
                {props.children}
            </Component>
        )
    }
    return {
        wrapper: <Result />
    }
}
const BlockRenderMap = DefaultDraftBlockRenderMap.merge(Immutable.Map({
    "header-one": headerWrapper(StyledHeaderOne),
    "header-two": headerWrapper(StyledHeaderTwo),
    "header-three": headerWrapper(StyledHeaderThree)
}))
/**
 * 可编辑
 * 初始值
 * 工具栏选择
 */
const RichEditor = ({
    value,
    readOnly = false,
    toolbars,
    onChange
}: any) => {
    const editorRef = useRef<Editor>(null)
    const [editorState, setEditorState] = useState(() => {
        return EditorState.createEmpty()
    })
    const onChangeEditorState = useCallback((editorState: EditorState) => {
        if (!!onChange) onChange(editorState)
        setEditorState(editorState);
    }, []);
    useEffect(() => {
        if (!editorRef.current) return;
        if (!editorRef.current.editor) return;
        editorRef.current.editor.style.minHeight = "300px"
    }, []);

    const blockStyleFn = useCallback((block: ContentBlock) => {
        const metaData = block.getData()
        const textAlign = metaData.get('align');
        let classes = [];
        if (!!textAlign) classes.push(`text-${textAlign}`);
        return classes.join(" ");
    }, []);
    const blockRendererFn = useCallback((block: ContentBlock) => {
        const type = block.getType();
        if (type === "atomic") {
            const entityKey = block.getEntityAt(0)
            if (!entityKey) return;
            const currentContent = editorState.getCurrentContent()
            const entity = currentContent.getEntity(entityKey);
            const entityType = entity.getType();
            const method = {
                editable: false,
                props: {
                    readOnly,
                    editorState,
                    onChange: onChangeEditorState
                },
                component: null as any,
            }
            switch (entityType) {
                case imageBlockName:
                    method.component = AtomicImage
                    break;
                default:
                    return;
            }
            return method;
        }
    }, [onChangeEditorState, editorState]);
    const [open, setOpen] = useState(false);
    const onOpen = useCallback(() => setOpen(true), []);
    const onCancel = useCallback(() => setOpen(false), []);
    const onTab = useCallback((e: React.KeyboardEvent) => {
        e.preventDefault();
        const newContentState = Modifier.replaceText(
            editorState.getCurrentContent(),
            editorState.getSelection(),
            "       "
        );
        onChangeEditorState(EditorState.push(editorState, newContentState, "insert-characters"));
    }, [editorState, onChangeEditorState]);
    return (
        <div>
            <UiModal
                onCancel={onCancel}
                title="test"
                open={open}
            >
                kgnb
            </UiModal>
            <UiButton onClick={onOpen}>
                button
            </UiButton>
            <RichEditorToolbar
                editorState={editorState}
                onChange={onChangeEditorState}
            />
            <Editor
                editorState={editorState}
                blockRendererFn={blockRendererFn}
                onTab={onTab}
                onChange={onChangeEditorState}
                readOnly={readOnly}
                blockStyleFn={blockStyleFn}
                ref={editorRef}
                blockRenderMap={BlockRenderMap}
            />
        </div>
    )
}
export default RichEditor